package com.hins.demo.order.executor;

import com.hins.component.dto.Response;
import com.hins.demo.convertor.OrderConvertor;
import com.hins.demo.dto.CheckoutCmd;
import com.hins.demo.factory.OrderFactory;
import com.hins.demo.gateway.InventoryGateway;
import com.hins.demo.gateway.ItemGateway;
import com.hins.demo.gateway.OrderGateway;
import com.hins.demo.model.order.Item;
import com.hins.demo.model.order.Order;

import javax.annotation.Resource;

/**
 * Description: 下单执行
 *
 * @author wenjiaqi
 * @date 2021/6/18 16:16
 */
public class CheckoutCmdExe {

    @Resource
    private ItemGateway itemGateway;

    @Resource
    private InventoryGateway inventoryGateway;

    @Resource
    private OrderGateway orderGateway;

    @Resource
    private OrderConvertor orderConvertor;

    @Resource
    private OrderFactory orderFactory;

    public Response execute(CheckoutCmd cmd) {
        Item item = itemGateway.getItem(cmd.getItemId());
        if (item == null) {
            return Response.buildFailure("999", "Item Not Found");
        }

        boolean withholdSuccess = inventoryGateway.withhold(cmd.getItemId(), cmd.getQuantity());
        if (!withholdSuccess) {
            return Response.buildFailure("999", "Inventory not enough");
        }

        Order order = orderFactory.create(cmd.getUserId(), item);

        Order savedOrder = orderGateway.save(order);

        return Response.buildSuccess();
    }
}
